package org.webcamp.settings.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.jdbc.core.JdbcTemplate;
import org.webcamp.settings.dao.SettingsDao;
import org.webcamp.settings.dto.Settings;

public class SettingsDaoImpl extends JdbcTemplate implements SettingsDao {

	@Override
	public Settings loadSettings() {
		Settings res = new Settings();
		Connection conn = null;
		try {
			conn = getDataSource().getConnection();

			PreparedStatement ps = conn.prepareStatement("select name, value from settings");
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				String name = rs.getString("name");
				String value = rs.getString("value");
				res.setSetting(name, value);
			}
			System.out.println("Settings were loaded");
			return res;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void saveSettings(Settings settings) {
		Connection conn = null;
		try {
			conn = getDataSource().getConnection();

			Statement st = conn.createStatement();
			st.executeUpdate("delete from settings");
			st.close();

			PreparedStatement ps = conn.prepareStatement("insert into settings (name, value) values (?,?)");
			for (String name : Settings.SETTINGS_NAMES) {
				String value = settings.getSetting(name);
				ps.setString(1, name);
				ps.setString(2, value);
				ps.addBatch();
			}
			ps.executeBatch();
			System.out.println("Settings were saved");
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/*
	 * private static final String SETTINGS_FILE_NAME = "xquesty.settings";
	 * 
	 * @Override public Settings loadSettings() { try { File file = new
	 * File(SETTINGS_FILE_NAME); FileInputStream fis = new
	 * FileInputStream(file); System.out.println(file.getCanonicalPath());
	 * ObjectInputStream ois = new ObjectInputStream(fis); Settings res =
	 * (Settings) ois.readObject(); ois.close(); return res; } catch (Exception
	 * e) { e.printStackTrace(); return new Settings(); } }
	 * 
	 * @Override public void saveSettings(Settings value) { try {
	 * FileOutputStream fos = new FileOutputStream(SETTINGS_FILE_NAME);
	 * ObjectOutputStream oos = new ObjectOutputStream(fos);
	 * oos.writeObject(value); oos.flush(); oos.close(); } catch (Exception e) {
	 * e.printStackTrace(); } }
	 */
}
